<template>
    <div>
      <div class="login">
        <div class="cover">
          <h1 class="title">找回密码</h1>
          <div class="input">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
              <el-form-item prop="email">
                <el-input class="input-item" v-model="ruleForm.email" placeholder="邮箱">
                  <template slot="prepend"><i class="iconfont icon-email" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="emailCode">
                <el-input  class="input-item" v-model="ruleForm.emailCode" placeholder="验证码">
                  <template slot="prepend"><i class="iconfont icon-code" style="font-size: 25px"></i></template>
                  <template slot="append">
                    <el-button v-if="code.status === 0" @click="getEmailCode">获取验证码</el-button>
                    <el-button v-if="code.status === 1" disabled>
                      获取<i class="el-icon-loading"></i>
                    </el-button>
                    <el-button v-if="code.status === 2" disabled>
                      {{code.countDown}}秒后重新获取
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="newPassword">
                <el-input  class="input-item" v-model="ruleForm.newPassword" placeholder="设置新的密码" show-password>
                  <template slot="prepend"><i class="el-icon-lock" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input  class="input-item" v-model="ruleForm.confirmPassword" placeholder="请再次输入密码" show-password>
                  <template slot="prepend"><i class="el-icon-lock" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="input-item" type="primary" v-if="processing" disabled>重置密码中...</el-button>
                <el-button class="input-item" type="primary" v-else @click="submitForm('ruleForm')">确认重置密码</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 表单
      ruleForm: {
        newPassword: '',
        confirmPassword: '',
        email: '',
        emailCode: ''
      },
      // 表单验证规则
      rules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,12}$/, message: '包含至少一个大写字母、一个小写字母和一个数字，长度为6到12', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '邮箱格式错误', trigger: 'blur' }
        ],
        emailCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ]
      },
      processing: false,
      code: {
        status: 0,
        countDown: 0,
        timer: null
      }
    }
  },
  methods: {
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.processing = true
          let params = new URLSearchParams()
          params.append('email', this.ruleForm.email)
          params.append('emailCode', this.ruleForm.emailCode)
          params.append('password', this.ruleForm.newPassword)
          this.axios.post('/api/v1/user/forgot', params).then((response) => {
            if (response.data.code === 1) {
              this.$message.success('修改成功！')
              this.$router.push('/')
            } else {
              this.processing = false
              this.$message.error(response.data.message)
              console.error(response.data.message)
            }
          }).catch((error) => {
            this.processing = false
            this.$message.error(error)
            console.error(error)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getEmailCode () {
      let email = this.ruleForm.email
      console.log('email = ' + email)
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (emailRegex.test(email)) {
        this.code.status = 1
        this.axios.get(`/api/v1/mail/verify_code?email=${email}`).then((response) => {
          if (response.data.code === 1) {
            this.code.status = 2
            this.$message.success('验证码发送成功!')
            this.startCountDown()
          } else {
            this.code.status = 0
            this.$message.error(response.data.message)
            console.error(response.data.message)
          }
        }).catch((error) => {
          this.code.status = 0
          this.processing = false
          this.$message.error(error)
          console.error(error)
        })
      } else {
        this.$alert('邮箱格式错误!', '提示', {
          confirmButtonText: '关闭',
          type: 'info',
          callback: action => {
          }
        })
      }
    },
    startCountDown () {
      // 假设点击获取验证码后，发送验证码请求，请求成功后执行以下代码
      // 启动倒计时
      this.code.countDown = 60
      this.code.timer = setInterval(() => {
        if (this.code.countDown > 0) {
          this.code.countDown--
        } else {
          this.code.status = 0
          clearInterval(this.code.timer)
        }
      }, 1000)
    },
    validateConfirmPassword (rule, value, callback) {
      if (value !== this.ruleForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.cascader .el-input__inner
  border none
.el-form-item
  margin-bottom 0
.cover
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-color rgba(0, 0, 0, 0.51)
  z-index 2
.login
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-image url("../assets/background.jpg")
  background-size cover
  background-repeat no-repeat
  .title
    padding-top 80px
    padding-bottom 30px
    text-align center
    font-size 35px
    font-weight bold
    color #ffffff
  .input
    min-width 200px
    max-width 400px
    margin 20px auto
    padding 20px
    border-radius 20px
    background white
    .input-item
      width 100%
      margin-top 20px
</style>
